package com.zues.thread.lock.readwrite;

import com.zues.thread.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 演示读写锁
 * @ClassName DataContainer
 * @Description TODO
 * @Author zeus
 * @Date 3/25/2025 2:49 下午
 * @Version 1.0
 **/
@Slf4j(topic = "c.DataContainer")
public class DataContainer {

    private Object data;

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private ReentrantReadWriteLock.ReadLock readLock = lock.readLock();

    private ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

//    public DataContainer(Object data) {
//        this.data = data;
//    }

    public Object read(){
        log.debug("获取读锁...");
        readLock.lock();
        try {
            log.debug("读取...");
            ThreadUtil.sleep(2);
        }finally {
            log.debug("释放读锁...");
            readLock.unlock();
        }



        return data;
    }

    public void write(){
        log.debug("获取写锁...");
        writeLock.lock();
        try {
            log.debug("写入...");
        }finally {
            log.debug("释放写锁...");
            writeLock.unlock();
        }



    }

}
